package com.yz.jdd.base.utils;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class GsonUtils {

    public static Object json2Obj(String json, Class<?> clazz) {
        if (TextUtils.isEmpty(json))
            return null;
        Gson gson = new Gson();
        return gson.fromJson(json, clazz);
    }

    public static <T> Object json2Obj(String json, TypeToken<T> typeToken) {
        Gson gson = new Gson();
        return gson.fromJson(json, typeToken.getType());
    }

    public static String obj2Json(Object obj) {
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
                .create();
        return gson.toJson(obj);
    }

    public static JSONObject json2JsonObject(String json) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    public static HashMap<String, String> JsonObject2HashMap(String jsonData) {
        JSONObject jsonObject = json2JsonObject(jsonData);
        HashMap<String, String> data = new HashMap<>();
        Iterator it = jsonObject.keys();
        // 遍历jsonObject数据，添加到Map对象
        while (it.hasNext()) {
            String key = String.valueOf(it.next());
            String value = null;
            try {
                value = (String) jsonObject.get(key);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            data.put(key, value);
        }
        return data;
    }

    public static <T> List<T> fromJsonArray(String json, Class<T> clazz) throws Exception {
        List<T> lst = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            lst.add(new Gson().fromJson(elem, clazz));
        }
        return lst;
    }


}
